package com.gr.dmbackend.service.Impl.sysadmin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.dmbackend.mapper.DormitoryMapper;
import com.gr.dmbackend.model.Dormitory;
import com.gr.dmbackend.service.sysadmin.UpdateDormitoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UpdateDormitoryServiceImpl implements UpdateDormitoryService {

    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public JSONObject updateDormitory(Map<String, String> data) {

        JSONObject resp = new JSONObject();

        int id = Integer.parseInt(data.get("id"));
        String dormId = data.get("dormId");
        String building = data.get("building");
        String floor = data.get("floor");

        if (dormId.isEmpty()) {
            resp.put("error_message", "寝室号不能为空");
            return resp;
        }
        if ("请选择楼栋".equals(building) || building.isEmpty()) {
            resp.put("error_message", "请选择楼栋");
            return resp;
        }
        if ("请选择楼层".equals(floor) || floor.isEmpty()) {
            resp.put("error_message", "请选择楼层");
            return resp;
        }
        if (dormId.length() > 10) {
            resp.put("error_message", "寝室号长度超出限制");
            return resp;
        }
        if (building.length() > 20) {
            resp.put("error_message", "楼栋长度超出限制");
            return resp;
        }
        if (floor.length() > 5) {
            resp.put("error_message", "楼层长度超出限制");
            return resp;
        }

        QueryWrapper<Dormitory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dorm_id", dormId)
                .eq("building", building);
        Dormitory item = dormitoryMapper.selectOne(queryWrapper);
        if (item != null) {
            resp.put("error_message", "寝室号已存在");
            return resp;
        }

        Dormitory dormitory = dormitoryMapper.selectById(id);
        if (dormitory == null) {
            resp.put("error_message", "当前宿舍不存在");
            return resp;
        }
        dormitory.setDormId(dormId);
        dormitory.setBuilding(building);
        dormitory.setFloor(floor);
        dormitoryMapper.updateById(dormitory);
        resp.put("error_message", "success");

        return resp;
    }
}
